/*
 * @Description: 动态表单控制器
 */
import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  HttpCode,
  HttpStatus,
  Req,
  Request,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
import { DynamicFormService } from './dynamic-form.service';
import { CreateFormTemplateDto } from './dto/create-form-template.dto';
import { UpdateFormTemplateDto } from './dto/update-form-template.dto';
import { AddFormFieldDto } from './dto/add-form-field.dto';
import { SubmitFormDto } from './dto/submit-form.dto';
import { QueryFormTemplateDto, QueryFormSubmissionDto } from './dto/query-form.dto';
import { Public } from 'src/decorations/public.decorator';

@ApiTags('动态表单')
@Controller('dynamic-form')
export class DynamicFormController {
  constructor(private readonly dynamicFormService: DynamicFormService) {}

  // ==================== 表单模板相关接口 ====================

  @Post('template')
  @ApiOperation({ summary: '创建表单模板' })
  @ApiResponse({ status: 201, description: '表单模板创建成功' })
  @ApiResponse({ status: 400, description: '请求参数错误' })
  @Public()
  async createFormTemplate(@Body() createFormTemplateDto: CreateFormTemplateDto) {
    return await this.dynamicFormService.createFormTemplate(createFormTemplateDto);
  }

  @Get('template')
  @ApiOperation({ summary: '获取表单模板列表' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async getFormTemplates(@Query() queryDto: QueryFormTemplateDto) {
    return await this.dynamicFormService.getFormTemplates(queryDto);
  }

  @Get('template/:id')
  @ApiOperation({ summary: '根据ID获取表单模板' })
  @ApiParam({ name: 'id', description: '表单模板ID' })
  @ApiResponse({ status: 200, description: '获取成功' })
  @ApiResponse({ status: 404, description: '表单模板不存在' })
  async getFormTemplateById(@Param('id') id: string) {
    return await this.dynamicFormService.getFormTemplateById(id);
  }

  @Get('template/key/:formKey')
  @ApiOperation({ summary: '根据表单标识符获取表单模板' })
  @ApiParam({ name: 'formKey', description: '表单标识符' })
  @ApiResponse({ status: 200, description: '获取成功' })
  @ApiResponse({ status: 404, description: '表单模板不存在' })
  async getFormTemplateByKey(@Param('formKey') formKey: string) {
    return await this.dynamicFormService.getFormTemplateByKey(formKey);
  }

  @Put('template/:id')
  @ApiOperation({ summary: '更新表单模板' })
  @ApiParam({ name: 'id', description: '表单模板ID' })
  @ApiResponse({ status: 200, description: '更新成功' })
  @ApiResponse({ status: 404, description: '表单模板不存在' })
  async updateFormTemplate(
    @Param('id') id: string,
    @Body() updateFormTemplateDto: UpdateFormTemplateDto,
  ) {
    return await this.dynamicFormService.updateFormTemplate(id, updateFormTemplateDto);
  }

  @Delete('template/:id')
  @ApiOperation({ summary: '删除表单模板' })
  @ApiParam({ name: 'id', description: '表单模板ID' })
  @ApiResponse({ status: 200, description: '删除成功' })
  @ApiResponse({ status: 404, description: '表单模板不存在' })
  async deleteFormTemplate(@Param('id') id: string) {
    return await this.dynamicFormService.deleteFormTemplate(id);
  }

  @Post('template/field')
  @ApiOperation({ summary: '向表单模板添加字段' })
  @ApiResponse({ status: 201, description: '字段添加成功' })
  @ApiResponse({ status: 400, description: '请求参数错误' })
  @ApiResponse({ status: 404, description: '表单模板不存在' })
  async addFormField(@Body() addFormFieldDto: AddFormFieldDto) {
    return await this.dynamicFormService.addFormField(addFormFieldDto);
  }

  @Delete('template/:formTemplateId/field/:fieldName')
  @ApiOperation({ summary: '从表单模板移除字段' })
  @ApiParam({ name: 'formTemplateId', description: '表单模板ID' })
  @ApiParam({ name: 'fieldName', description: '字段名' })
  @ApiResponse({ status: 200, description: '字段移除成功' })
  @ApiResponse({ status: 404, description: '表单模板或字段不存在' })
  async removeFormField(
    @Param('formTemplateId') formTemplateId: string,
    @Param('fieldName') fieldName: string,
  ) {
    return await this.dynamicFormService.removeFormField(formTemplateId, fieldName);
  }

  // ==================== 表单提交相关接口 ====================

  @Post('submit')
  @ApiOperation({ summary: '提交表单数据' })
  @ApiResponse({ status: 201, description: '表单提交成功' })
  @ApiResponse({ status: 400, description: '表单数据验证失败' })
  @ApiResponse({ status: 404, description: '表单模板不存在' })
  @HttpCode(HttpStatus.CREATED)
  async submitForm(@Body() submitFormDto: SubmitFormDto, @Req() req: Request) {
    // 自动获取IP地址和用户代理
    // @ts-ignore
    const clientIp = req.ip || req.connection.remoteAddress || req.socket.remoteAddress;
    // @ts-ignore
    const userAgent = req.get('User-Agent');

    const enhancedSubmitDto = {
      ...submitFormDto,
      submitterIp: submitFormDto.submitterIp || clientIp,
      userAgent: submitFormDto.userAgent || userAgent,
      source: submitFormDto.source || 'web',
    };

    return await this.dynamicFormService.submitForm(enhancedSubmitDto);
  }

  @Get('submission')
  @ApiOperation({ summary: '获取表单提交记录列表' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async getFormSubmissions(@Query() queryDto: QueryFormSubmissionDto) {
    return await this.dynamicFormService.getFormSubmissions(queryDto);
  }

  @Get('submission/:id')
  @ApiOperation({ summary: '根据ID获取表单提交记录' })
  @ApiParam({ name: 'id', description: '提交记录ID' })
  @ApiResponse({ status: 200, description: '获取成功' })
  @ApiResponse({ status: 404, description: '提交记录不存在' })
  async getFormSubmissionById(@Param('id') id: string) {
    return await this.dynamicFormService.getFormSubmissionById(id);
  }

  @Put('submission/:id/status')
  @ApiOperation({ summary: '更新提交记录状态' })
  @ApiParam({ name: 'id', description: '提交记录ID' })
  @ApiResponse({ status: 200, description: '状态更新成功' })
  @ApiResponse({ status: 404, description: '提交记录不存在' })
  async updateSubmissionStatus(
    @Param('id') id: string,
    @Body() body: { status: string; processNote?: string; processedBy?: string },
  ) {
    const { status, processNote, processedBy } = body;
    return await this.dynamicFormService.updateSubmissionStatus(id, status, processNote, processedBy);
  }

  // ==================== 统计相关接口 ====================

  @Get('statistics/template/:id')
  @ApiOperation({ summary: '获取表单模板统计信息' })
  @ApiParam({ name: 'id', description: '表单模板ID' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async getTemplateStatistics(@Param('id') id: string) {
    // 获取该表单的提交统计
    const submissions = await this.dynamicFormService.getFormSubmissions({
      formTemplateId: id,
      page: 1,
      limit: 1000, // 获取足够多的数据用于统计
    });

    const statusStats = submissions.data.reduce((acc, submission) => {
      const status = submission.status || 'submitted';
      acc[status] = (acc[status] || 0) + 1;
      return acc;
    }, {});

    return {
      totalSubmissions: submissions.total,
      statusStatistics: statusStats,
      recentSubmissions: submissions.data.slice(0, 10), // 最近10条提交
    };
  }

  @Get('statistics/overview')
  @ApiOperation({ summary: '获取动态表单系统概览统计' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async getOverviewStatistics() {
    const templates = await this.dynamicFormService.getFormTemplates({ page: 1, limit: 1000 });
    const submissions = await this.dynamicFormService.getFormSubmissions({ page: 1, limit: 1000 });

    const activeTemplates = templates.data.filter(t => t.isActive).length;
    const inactiveTemplates = templates.data.filter(t => !t.isActive).length;

    return {
      totalTemplates: templates.total,
      activeTemplates,
      inactiveTemplates,
      totalSubmissions: submissions.total,
      recentTemplates: templates.data.slice(0, 5),
      recentSubmissions: submissions.data.slice(0, 10),
    };
  }
}